package com.uenpay.im.zxing;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.SessionModel;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.socks.library.KLog;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.WebViewActivity;
import com.uenpay.im.ui.old.activity.chat.ChatActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.contacts.UserDetailActivity;
import com.uenpay.im.ui.old.activity.group.GroupMangerHandler;
import com.uenpay.im.ui.old.activity.group.InvitJoinGroupDetailActivity;
import com.uenpay.im.ui.old.activity.group.NotJoinGroupActivity;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.invokeitems.HttpRequestHandle;
import com.uenpay.im.zxing.decoding.CaptureActivityHandler;
import com.uenpay.im.zxing.decoding.InactivityTimer;
import com.uenpay.im.zxing.view.ViewfinderView;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.common.StringUtils;
import com.uenpay.util.crypt.SafeUrlCrypt;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Vector;

import static com.uenpay.im.zxing.camera.CameraManager.get;
import static com.uenpay.im.zxing.camera.CameraManager.init;

/**
 * Initial the camera
 *
 * @author Ryan.Tang
 */
public class CaptureActivity extends BaseActivity implements Callback {

    public static final int REQUEST_CODE_TRANFER = 101;

    private String soundName = "";
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer BackgroundMediaPlayer;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);

    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_scanning;
    }

    @Override
    public void initView(View view) {
        init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        ((TextView) findViewById(R.id.title_textview)).setText(R.string.sweep);
        ((TextView) findViewById(R.id.title_right_tv)).setText(R.string.album);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        finish();
                    }
                });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent getImage = new Intent(CaptureActivity.this,
                                PhotoActivity.class);
                        getImage.putExtra("selected_count", 0);
                        getImage.putExtra("max_select_count", 1);
                        startActivityForResult(getImage, 100);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == 100) {
            ArrayList<PhotoItem> select_gl_arr = (ArrayList<PhotoItem>) data
                    .getSerializableExtra("gl_arr");
            if (select_gl_arr.size() > 0) {
                for (int i = 0; i < select_gl_arr.size(); i++) {
                    String path = select_gl_arr.get(i).getPath();
                    Result mResult = paresQRciseBitmap(path);
                    if (mResult != null) {
                        handleDecode(mResult, null);
                    } else {
                        IMApplication.showToast(R.string.sweep_no_result);
                    }
                }
            }
        } else if (requestCode == REQUEST_CODE_TRANFER) {
            finish();
        }
    }

    private Result paresQRciseBitmap(String bitmapPath) {
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);
        options.inSampleSize = options.outHeight / 400;
        if (options.inSampleSize <= 0) {
            options.inSampleSize = 1;
        }
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(bitmapPath, options);
        RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
                rgbLuminanceSource));
        QRCodeReader reader = new QRCodeReader();
        Result result = null;
        try {
            result = reader.decode(binaryBitmap);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playSound("play_completed.mp3", false);
        String resultString = result.getText();
        KLog.d("[handleDecode] result:" + resultString);
        if (!TextUtils.isEmpty(resultString)) {
            getCaptureResult(resultString);
        }
    }

    private void analysisException(String result) {
        String start_str = result;
        try {
            boolean iSO = Charset.forName("ISO-8859-1").newEncoder()
                    .canEncode(start_str);
            if (iSO) {
                start_str = new String(start_str.getBytes("ISO-8859-1"), "GBK");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        String temp_str = start_str.toLowerCase(Locale.getDefault());
        if (Utils.getUrl(temp_str)) {
            // Intent intent = new Intent();
            // intent.setAction("android.intent.action.VIEW");
            // Uri content_url = null;
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            // content_url = Uri.parse(result.toString());
            // intent.setData(content_url);
            // startActivity(intent);

            Intent intent2 = new Intent(CaptureActivity.this,
                    WebViewActivity.class);
            if (!temp_str.startsWith("http") || !temp_str.startsWith("HTTP")) {
                temp_str = "http://" + temp_str;
            }
            intent2.putExtra("url", temp_str);
            startActivity(intent2);
        } else {
            Intent intent = new Intent();
            intent.putExtra("content", start_str);
            intent.setClass(CaptureActivity.this, OtherContentActivity.class);
            startActivity(intent);
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void playSound(String name, boolean isLoop) {
        if (BackgroundMediaPlayer == null) {
            BackgroundMediaPlayer = new MediaPlayer();
        }
        if (BackgroundMediaPlayer != null) {
            if (name.equalsIgnoreCase(soundName)) {
                if (!BackgroundMediaPlayer.isPlaying()) {
                    BackgroundMediaPlayer.start();
                }
                return;
            }
            BackgroundMediaPlayer.stop();
            BackgroundMediaPlayer.reset();
            BackgroundMediaPlayer.setLooping(isLoop);

            AssetManager am = getAssets();
            try {
                AssetFileDescriptor afd = am.openFd(name);
                BackgroundMediaPlayer.setDataSource(afd.getFileDescriptor(),
                        afd.getStartOffset(), afd.getLength());
                BackgroundMediaPlayer.prepare();
                BackgroundMediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        soundName = name;
    }

    private void checkExitInGroup(final String chatId, final String userName,
                                  final int custNum, final int chattype) {
        GroupMangerHandler mHandler = new GroupMangerHandler();
        mHandler.checkExitInGroup(chatId, new GroupMangerHandler.IAutoJoinListener() {

            @Override
            public void onAutoJoinResult(int status, String msg) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    if (chattype == 3) {
                        Intent intent = new Intent(CaptureActivity.this,
                                InvitJoinGroupDetailActivity.class);
                        intent.putExtra("chatid", chatId);
                        startActivity(intent);
                        finish();
                    } else {
                        Intent intent = new Intent(CaptureActivity.this,
                                NotJoinGroupActivity.class);
                        intent.putExtra("chat_id", chatId);
                        intent.putExtra("chat_name", userName);
                        intent.putExtra("cust_name", custNum);
                        startActivity(intent);
                        finish();
                    }

                } else if (status == HttpInvokeResultCode.IN_THE_GORUP) {
                    Intent intent = new Intent(CaptureActivity.this,
                            ChatActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    Bundle bu = new Bundle();
                    SessionModel sessionModel = new SessionModel();
                    sessionModel.setSessionId(Long.valueOf(chatId));
                    sessionModel.setSessionType(PacketType.GROUP);
                    bu.putParcelable("session", sessionModel);
                    bu.putString("stranger_name", userName);
                    intent.putExtras(bu);
                    startActivity(intent);
                    finish();
                } else if (TextUtils.isEmpty(msg)) {
                    IMApplication.showToast(msg);
                }
            }
        });
    }

    private void getCaptureResult(String url) {
        if (url.startsWith(APIConfiguration.getQrCodeUrl())) {
            // TODO
            checkCaptureUrl(url);
        } else if (url.startsWith(APIConfiguration.getUenQrCodeUrl())) {
            if (url.contains("#")) {
                parsePayCodeInfo(url);
            } else if (url.endsWith("$0")) {
                //付款码二维码
                showAlertDialog();
            }
        } else {
            String newUrl = url.replace(" ", "");
            if (newUrl.length() == 18 && StringUtils.isNumeric(newUrl)) {
                //付款码条形码
            } else {
                analysisException(url);
            }
        }
    }

    
    /**
     * 检查地址结果
     *
     * @param url
     */
    private void checkCaptureUrl(String url) {
        CaptureInvokeItem item = new CaptureInvokeItem(url);
        HttpRequestHandle.onBaseRequest(item, HttpRequestType.SERVER_ONLY,
                new HttpRequestHandle.IRequestResultListener() {
                    @Override
                    public void onResult(Object resultObject, boolean isCache,
                                         String failReason) {
                        if (resultObject == null) {

                        } else {
                            CaptureInvokeItem.CaptureInvokeItemResult result = ((CaptureInvokeItem) resultObject)
                                    .getOutPut();
                            if (result != null) {
                                if (result.status == HttpInvokeResultCode.RESULT_OK
                                        && result.body != null) {
                                    handleCaptureResult(result.controller,
                                            result.body);
                                } else if (!TextUtils.isEmpty(result.msg)) {
                                    IMApplication.showToast(result.msg);
                                }
                            } else {

                            }
                        }
                    }
                });
    }

    /**
     * 解析二维码中传来的信息
     * 格式: http://api2.qiyunxin.com/Communal/Communal/getQrCodeInfo?data=kHpau0RnSF15tJ78ZHmzO5BEWhNeoCRCnKhIXIPPn2KLfQOU9xsNywz7TlolavN_mdz3tY1PxK-cTbgrdExgDx6RziUPE0UBP0cdvoi9UgYpJ3fkxH4Bj-18JdpZmqeY#
     *
     * @param url
     */
    private void parsePayCodeInfo(String url) {
        String amount = "";
        if (url.indexOf("#") != url.length() - 1) {
            amount = url.split("#")[1];
        }
        String data = url.split("=")[1].split("#")[0];
        KLog.d("[parsePayCodeInfo] data=" + SafeUrlCrypt.decryptByAes(data, SafeUrlCrypt.KEY));
        String custId = "";
        String nickName = "";
        try {
            JSONObject jsonObject = new JSONObject(SafeUrlCrypt.decryptByAes(data, SafeUrlCrypt.KEY));
            if (jsonObject != null) {
                if (jsonObject.has("custid")) {
                    custId = jsonObject.getString("custid");
                }

                if (jsonObject.has("nickname")) {
                    nickName = jsonObject.getString("nickname");
                }
                ARouter.getInstance().build("/trans/transfer").withString("custid", custId).withString("nickname", nickName).withString("amount", amount).navigation(this, REQUEST_CODE_TRANFER);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void handleCaptureResult(String controller, JSONObject json) {
        if (controller.equals("Cust")) {
            String custId = "";
            if (json.has("custid")) {
                custId = json.optString("custid");
            }
            if (!TextUtils.isEmpty(custId)) {
                Intent intent = new Intent();
                intent.setClass(CaptureActivity.this, UserDetailActivity.class);
                intent.putExtra("cust_id", custId);
                startActivity(intent);
                finish();
            }
        } else if (controller.equals("Chat")) {
            String chatid = "";
            String chatName = "";
            int custNum = 0;
            int chattype = 0;
            if (json.has("chatid")) {
                chatid = json.optString("chatid");
            }
            if (json.has("chatname")) {
                chatName = json.optString("chatname");
            }
            if (json.has("custnum")) {
                custNum = json.optInt("custnum");
            }
            if (json.has("chattype")) {
                chattype = json.optInt("chattype");
            }
            if (!TextUtils.isEmpty(chatid)) {
                checkExitInGroup(chatid, chatName, custNum, chattype);
            }
        } else {
            analysisException(json.toString());
        }
    }

    private void showAlertDialog() {
        new AlertDialog.Builder(this)
                .setMessage("该码仅供对方付款给商家，如需像TA付款，请TA使用\"收款码\"功能")
                .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }


    // private void getGroupDetail(final String chatId,final String
    // custNum,final String userName){
    // GroupMangerHandler mHandler = new GroupMangerHandler();
    // mHandler.getNewGroup(chatId, new OnGetGroupTalk() {
    //
    // @Override
    // public void onSucceeful(String status, GetGroupMessageDetailResult
    // result) {
    // if(result != null){
    // if(result.groupTalk.org_type_id == 3){
    // Intent intent = new Intent(CaptureActivity.this,
    // InvitJoinGroupDetailActivity.class);
    // intent.putExtra("chat_id", chatId);
    // intent.putExtra("chat_name",userName);
    // intent.putExtra("cust_name", custNum);
    // startActivity(intent);
    // finish();
    // }else{
    // Intent intent = new Intent(CaptureActivity.this,
    // NotJoinGroupActivity.class);
    // intent.putExtra("chat_id", chatId);
    // intent.putExtra("chat_name",userName);
    // intent.putExtra("cust_name", custNum);
    // startActivity(intent);
    // finish();
    // }
    // }
    // }
    //
    // @Override
    // public void onFailed(String status) {
    //
    // }
    // });
    // }

}